package com.h3c.ptability.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.UserUtils;
import com.h3c.it.common.misc.lang.Assert;
import com.h3c.ptability.client.EosSyncDataClient;
import com.h3c.ptability.dto.PtManagementAllDTO;
import com.h3c.ptability.entity.PtDept;
import com.h3c.ptability.entity.PtManagementAll;
import com.h3c.ptability.mapper.PtManagementAllMapper;
import com.h3c.ptability.service.IPtManagementAllService;
import com.h3c.ptability.support.PageQuery;
import com.h3c.ptability.utils.AppBusinessException;
import com.h3c.ptability.utils.FieldUtils;
import com.h3c.ptability.utils.MybatisUtils;
import com.h3c.ptability.vo.PtManagementAllVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * PtManagementAllServiceImpl 实现类
 *
 * @author h24002
 * @date 2023-05-05
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class PtManagementAllServiceImpl extends ServiceImpl<PtManagementAllMapper, PtManagementAll> implements IPtManagementAllService {

    private final PtManagementAllMapper ptManagementAllMapper;

    /**
     * eos服务
     */
    @Resource
    EosSyncDataClient eosSyncDataClient;

    /**
     * 用户公共类
     */
    @Resource
    private UserUtils userUtils;
    /**
     * 公共账户
     */
    @Value("${inventory.account}")
    private String inventoryAccount;
    /**
     * 公共密码
     */
    @Value("${inventory.password}")
    private String inventoryPassword;

    /**
     * 根据条件查询集合--分页
     *
     * @param pageQuery 查询条件
     * @return 主管信息集合--分页
     */
    @Override
    public IPage<PtManagementAllVO> selectPage(PageQuery<PtManagementAllDTO> pageQuery) {
        // 设置分页
        Page<PtManagementAll> page = new Page<>(pageQuery.getPageNum(), pageQuery.getPageSize());
        PtManagementAllDTO condition = pageQuery.getCondition();
        // 添加搜索条件
        LambdaQueryWrapper<PtManagementAll> queryWrapper = getQueryWrapper(condition);
        // 添加排序
        MybatisUtils.setOrderBy(page, pageQuery.getSortList());
        // 查询
        Page<PtManagementAll> ptManagementAllPage = ptManagementAllMapper.selectPage(page, queryWrapper);
        // 转化成vo
        List<PtManagementAllVO> ptManagementAllVOList = BeanUtil.copyToList(ptManagementAllPage.getRecords(), PtManagementAllVO.class);
        // 转化IPage
        return MybatisUtils.changeIPage(ptManagementAllPage, ptManagementAllVOList);
    }

    private LambdaQueryWrapper<PtManagementAll> getQueryWrapper(PtManagementAllDTO condition) {
        LambdaQueryWrapper<PtManagementAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.hasText(condition.getDeptManagerId()), PtManagementAll::getDeptManagerId, condition.getDeptManagerId())
                .eq(StringUtils.hasText(condition.getDeptManagerName()), PtManagementAll::getDeptManagerName, condition.getDeptManagerName())
                .eq(StringUtils.hasText(condition.getPostTypeCode()), PtManagementAll::getPostTypeCode, condition.getPostTypeCode())
                .eq(StringUtils.hasText(condition.getPostTypeName()), PtManagementAll::getPostTypeName, condition.getPostTypeName())
                .eq(condition.getDeptId() != null, PtManagementAll::getDeptId, condition.getDeptId())
                .eq(condition.getDeptLevel() != null, PtManagementAll::getDeptLevel, condition.getDeptLevel())
                .eq(condition.getIsMainDuty() != null, PtManagementAll::getIsMainDuty, condition.getIsMainDuty())
                .eq(condition.getIsMainPost() != null, PtManagementAll::getIsMainPost, condition.getIsMainPost());
        return queryWrapper;
    }

    /**
     * 添加数据
     *
     * @param dto 条件
     */
    @Override
    public void insert(PtManagementAllDTO dto) {
        // 转化类型
        PtManagementAll ptManagementAll = BeanUtil.copyProperties(dto, PtManagementAll.class);
        // 检查字段
        FieldUtils.checkFieldsExclude(ptManagementAll);
        // 添加
        this.save(ptManagementAll);
    }

    /**
     * 更新数据
     *
     * @param dto 条件
     */
    @Override
    public void update(PtManagementAllDTO dto) {
        // 转化类型
        PtManagementAll ptManagementAll = BeanUtil.copyProperties(dto, PtManagementAll.class);
        // 检查字段
        FieldUtils.checkFields(ptManagementAll);
        LambdaQueryWrapper<PtManagementAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PtManagementAll::getDeptManagerId, ptManagementAll.getDeptManagerId())
                .eq(PtManagementAll::getDeptId, ptManagementAll.getDeptId());
        Integer count = ptManagementAllMapper.selectCount(queryWrapper);
        if (count == 0) {
            throw new AppBusinessException("该数据不存在");
        }
        ptManagementAllMapper.update(ptManagementAll, queryWrapper);
    }

    /**
     * 同步数据
     *
     * @author h24002
     * @date 2023-05-05
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncAllManager() {
        try {
            String eosToken = userUtils.getToken(inventoryAccount, inventoryPassword);
            JSONObject allManager = eosSyncDataClient.getAllManager("Bearer " + eosToken);
            JSONArray jsonArray = allManager.getJSONArray("data");
            List<PtManagementAll> managementAllList = JSONArray.parseArray(jsonArray.toJSONString(), PtManagementAll.class);
            if (!CollectionUtils.isEmpty(managementAllList)) {
                ptManagementAllMapper.delete(null);
                saveBatch(managementAllList);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppBusinessException("同步失败");
        }
    }

    /**
     * 根据条件查询集合
     *
     * @param dto 条件
     * @return 主管信息集合
     */
    @Override
    public List<PtManagementAll> selectList(PtManagementAllDTO dto) {
        if (dto != null) {
            LambdaQueryWrapper<PtManagementAll> queryWrapper = getQueryWrapper(dto);
            return ptManagementAllMapper.selectList(queryWrapper);
        }
        return ptManagementAllMapper.selectList(null);
    }

    /**
     * 根据主管类别、兼岗类型、正副职查询集合
     *
     * @param manageTypes 主管类别
     * @param isMainPost  是否主兼岗
     * @param isMainDuty  是否正副职
     * @return 主管信息集合
     */
    @Override
    public List<PtDept> selectListByPostTypeCodes(List<String> manageTypes, Boolean isMainPost, Boolean isMainDuty) {
        List<PtDept> deptList = new ArrayList<>();
        LambdaQueryWrapper<PtManagementAll> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(!CollectionUtils.isEmpty(manageTypes), PtManagementAll::getPostTypeCode, manageTypes)
                .eq(isMainDuty != null, PtManagementAll::getIsMainDuty, isMainDuty)
                .eq(isMainPost != null, PtManagementAll::getIsMainPost, isMainPost);
        List<PtManagementAll> manageAllList = ptManagementAllMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(manageAllList)) {
            for (PtManagementAll item : manageAllList) {
                PtDept dept = new PtDept();
                dept.setDeptId(item.getDeptId());
                dept.setDeptLevel(item.getDeptLevel());
                dept.setDeptName(item.getDeptName());
                dept.setDeptManagerName(item.getDeptManagerName());
                dept.setDeptManagerId(item.getDeptManagerId());
                deptList.add(dept);
            }
        }
        return deptList;
    }
}
